package org.example.hospital_frontend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.hospital_frontend.domain.MedicalRecord;
import org.example.hospital_frontend.domain.Register;
import org.example.hospital_frontend.domain.User;
import org.example.hospital_frontend.mapper.MedicalRecordMapper;
import org.example.hospital_frontend.mapper.RegisterMapper;
import org.example.hospital_frontend.mapper.UserMapper;
import org.example.hospital_frontend.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MedicalRecordMapper medicalRecordMapper;

    @Autowired
    private RegisterMapper registerMapper;

    @Override
    public Map<String, Object> getBasicStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 总用户数
        result.put("totalUsers", userMapper.selectCount(null));
        
        // 总病历数
        result.put("totalMedicalRecords", medicalRecordMapper.selectCount(null));
        
        // 今日挂号数
        LocalDateTime today = LocalDate.now().atStartOfDay();
        QueryWrapper<Register> todayWrapper = new QueryWrapper<>();
        todayWrapper.ge("register_time", today);
        result.put("todayRegisters", registerMapper.selectCount(todayWrapper));
        
        // 待就诊数
        QueryWrapper<Register> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("status", 0);
        result.put("pendingRegisters", registerMapper.selectCount(pendingWrapper));
        
        return result;
    }

    @Override
    public Map<String, Object> getRegisterTrend() {
        Map<String, Object> result = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        
        // 获取最近7天的日期
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        
        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            dates.add(date.format(formatter));
            
            // 查询每天的挂号数
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.plusDays(1).atStartOfDay();
            
            QueryWrapper<Register> wrapper = new QueryWrapper<>();
            wrapper.between("register_time", startOfDay, endOfDay);
            counts.add(Math.toIntExact(registerMapper.selectCount(wrapper)));
        }
        
        result.put("dates", dates);
        result.put("counts", counts);
        return result;
    }

    @Override
    public Map<String, Object> getDoctorStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取所有医生的接诊统计
        List<Map<String, Object>> doctorStats = medicalRecordMapper.selectDoctorStatistics();
        
        List<String> doctors = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        
        for (Map<String, Object> stat : doctorStats) {
            doctors.add((String) stat.get("doctor_name"));
            counts.add(((Long) stat.get("count")).intValue());
        }
        
        result.put("doctors", doctors);
        result.put("counts", counts);
        return result;
    }

    @Override
    public Map<String, Object> getDiagnosisDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取所有诊断结果及其出现次数
        List<Map<String, Object>> diagnosisStats = medicalRecordMapper.selectDiagnosisStatistics();
        
        List<Map<String, Object>> data = diagnosisStats.stream()
            .map(stat -> {
                Map<String, Object> item = new HashMap<>();
                item.put("diagnosis", stat.get("diagnosis"));
                item.put("count", ((Long) stat.get("count")).intValue());
                return item;
            })
            .collect(Collectors.toList());
        
        result.put("data", data);
        return result;
    }

    @Override
    public Map<String, Object> getAgeDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        // 定义年龄区间
        String[] ageRanges = {"0-18", "19-30", "31-45", "46-60", "60+"};
        List<Integer> counts = new ArrayList<>();
        
        // 获取每个年龄区间的患者数量
        for (String range : ageRanges) {
            int count = userMapper.selectCountByAgeRange(range);
            counts.add(count);
        }
        
        result.put("ageRanges", ageRanges);
        result.put("counts", counts);
        return result;
    }
} 